#include "../common/Socket.hpp"
#include "../src/Connection.hpp"
#include "../src/Poller.hpp"
#include "../src/EventLoop.hpp"
#include "../common/logger.hpp"
#include "../src/Acceptor.hpp"
#include "../src/LoopThread.hpp"
#include "../common/LoggerHelper.hpp"
#include "../src/LoopThreadPoll.hpp"
#include "../src/TcpServer.hpp"

LoggerHelper logger_helper;


std::unordered_map<uint64_t, Connection::PtrConnection> connections;
uint64_t conn_id = 1;

EventLoop baseLoop;
LoopThreadPoll * loop_pool;




void destroy_connection(const Connection::PtrConnection& conn)
{
    connections.erase(conn->get_connect_id());
}

void on_connected(const Connection::PtrConnection& conn)
{
    LOG_DEBUG("new 了一个 Connection 对象 : conn_id : {}", conn->get_connect_id());
}

void on_message(const Connection::PtrConnection& conn, Buffer* buf)
{
    LOG_DEBUG("有消息到来 {}", buf->read_string_pop(buf->get_readable_size()));
    std::string response = "hello client !";
    conn->send(response.c_str(), response.size());
    // conn->shutdown();
}   




void new_connection(int fd)
{
    conn_id++;
    Connection::PtrConnection conn ( new Connection(loop_pool->next_loop(),conn_id ,fd) );
    conn->set_message_callback(std::bind(on_message, std::placeholders::_1, std::placeholders::_2));
    conn->set_connected_callback(on_connected);
    conn->set_server_closed_callback(std::bind(destroy_connection, std::placeholders::_1));
    conn->enable_inactive_release(10);
    conn->established(); 
    connections.insert(std::make_pair(conn_id, conn));
    
}

int main()
{
    loop_pool = new LoopThreadPoll(&baseLoop);
    loop_pool->set_thread_count(2);
    loop_pool->create();
    Acceptor acceptor(&baseLoop, 8080);
    acceptor.set_accept_callback(std::bind(new_connection ,std::placeholders::_1));
    acceptor.accept();

    baseLoop.start();
        
    return 0;
}